 <template>
  <div>
    <el-form ref="wyform" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="品牌名" prop="name">
        <el-input v-model="form.name" placeholder="请输入品牌名"></el-input>
      </el-form-item>
      <el-form-item label="品牌说明" prop="description">
        <VueEditor
          useCustomImageHandler
          v-model="form.description"
          @image-added="handleImageAdded"></VueEditor>
      </el-form-item>
       <el-form-item>
         <el-button type="success" size="small" plain @click="save">保存</el-button>
       </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { VueEditor } from 'vue2-editor'
import { post, get, asyncRequest } from '@/plugins/axios'
export default {
  name: 'BrandEdit',
  props: ['id', 'module'],
  components: {
    VueEditor
  },
  created () {
    if (this.id) {
      this.getone()
    }
  },
  data () {
    const checkData = async (rule, value, callback) => {
      const response = await asyncRequest(this.module + '/check', 'get', { value: value, id: this.id })
      if (response.data.obj) {
        callback()
      } else {
        callback(new Error('已经存在相同数据'))
      }
    }
    return {
      url: {
        add: this.module + '/add',
        update: this.module + '/update',
        getone: this.module + '/getone'
      },
      form: {
        name: '',
        description: ''
      },
      fileList: [],
      rules: {
        name: [
          { required: true, message: '请输入品牌名', trigger: 'blur' },
          { max: 20, message: '品牌名最多20个字符', trigger: 'blur' },
          { validator: checkData, trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入品牌说明', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    save () {
      // 先验证整个表单 如果有一个不通过都不能提交post请求
      this.$refs.wyform.validate((valid) => {
        if (valid) {
          post(this.id ? this.url.update : this.url.add, this.form, response => {
            this.$emit('update:show', false)
            this.$emit('getTableData')
          })
        }
      })
    },
    getone () {
      get(this.url.getone, { id: this.id }, response => {
        for (const key in this.form) {
          this.form[key] = response[key]
        }
        this.form.id = response.id
        this.fileList.push({
          name: response.icon,
          url: this.img(response.icon)
        })
      })
    },
    changeIcon (file) {
      this.form.file = file.raw
    },
    removeIcon () {
      this.form.file = null
    },
    handleImageAdded (file, Editor, cursorLocation, resetUploader) {
      post('/pms-file/upload', { file: file, bucket: 'img' }, response => {
        const url = this.img(response)
        console.log(url)
        Editor.insertEmbed(cursorLocation, 'image', url)
        resetUploader()
      })
	  
    }
  }
}
</script>

<style scoped lang="less">
</style>
